package com.yanghui.dtracing.core.utils;

import com.yanghui.dtracing.core.exception.PluginException;

import java.io.File;
import java.net.URL;

public class AgentPackagePath {
	
	public static File getPath() {
		String classResourcePath = AgentPackagePath.class.getName().replaceAll("\\.", "/") + ".class";
        URL resource = ClassLoader.getSystemClassLoader().getResource(classResourcePath);
        if (resource != null) {
            String urlString = resource.toString();

            int insidePathIndex = urlString.indexOf('!');
            boolean isInJar = insidePathIndex > -1;

            if (isInJar) {
                urlString = urlString.substring(urlString.indexOf("file:"), insidePathIndex);
                File agentJarFile = null;
                try {
                    agentJarFile = new File(new URL(urlString).toURI());
                } catch (Exception e) {
                	e.printStackTrace();
                    System.err.println("Can not locate agent jar file by url:" + urlString);
                }
                if (agentJarFile.exists()) {
                    return agentJarFile.getParentFile();
                }
            } else {
                int prefixLength = "file:".length();
                String classLocation = urlString.substring(
                    prefixLength, urlString.length() - classResourcePath.length());
                return new File(classLocation);
            }
        }
        throw new PluginException("Can not locate agent jar file.");
	}
}
